import threading
import time

def worker_function(shared_variable, stop_event, lock):
    while not stop_event.is_set():
        with lock:
            shared_variable += 1
        print("thread variable set to: %d" % shared_variable)
        time.sleep(1)


# 共享变量
shared_variable = 0

# 创建Event对象，用于通知子线程终止
stop_event = threading.Event()

# 创建锁
lock = threading.Lock()

# 创建子线程并启动
my_thread = threading.Thread(target=worker_function,
                             args=(shared_variable, stop_event, lock))
my_thread.start()

# 主线程尝试读取并输出子线程的变量
while shared_variable <= 5:
    with lock:
        print(f"Main thread: Shared variable = {shared_variable}")
    time.sleep(1)

# 通知子线程终止
stop_event.set()

# 等待子线程结束
my_thread.join()

print("Main thread finished.")
